﻿#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion

using System.Web.Mvc;
using Lokad.Monitoring.BusinessLogic;
using Lokad.Monitoring.Persistence.Entities;
using Lokad.Monitoring.Persistence.Repositories;

namespace Lokad.Monitoring.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        private readonly ReportRepository _reports;

        public HomeController()
        {
            _reports = GlobalSetup.Container.Resolve<ReportRepository>();
        }

        [AuthorizeOrRedirect]
        public ActionResult Index()
        {
            return View(_reports.List());
        }

        public ActionResult Json()
        {
            return View(_reports.List());
        }

        [AuthorizeOrRedirect]
        public ActionResult Report(string id)
        {
            ViewData["name"] = id;

            // retrieving the latest or regenerating the report
            var doc = _reports.Latest(id) ?? _reports.Generate(id);
            return View(doc);
        }

        [AuthorizeOrRedirect]
        public ActionResult ForceRefresh(string id)
        {
            ViewData["name"] = id;

            var doc = _reports.Generate(id);
            return View("Report", doc);
        }

        [AuthorizeOrRedirect]
        public ActionResult Create()
        {
            return View(
                new Report // default settings
                    {
                        MaxDays = 30,
                        IndicatorFaultTags = "fault",
                        MessageFaultTags = "fault"
                    });
        }

        [AuthorizeOrRedirect]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Report report)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            _reports.Create(report);
            return RedirectToAction("Index", _reports.List());
        }

        [AuthorizeOrRedirect]
        public ActionResult Edit(string id)
        {
            return View(_reports.Edit(id));
        }

        [AuthorizeOrRedirect]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string id, Report report)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            _reports.Edit(id, report);
            return RedirectToAction("Index");
        }

        [AuthorizeOrRedirect]
        public ActionResult Delete(string id)
        {
            _reports.Delete(id);
            return RedirectToAction("Index");
        }
    }
}
